package com.sx.gongzhong.widget;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;

/**
 * Created by admin on 2017/12/28.
 */

public class CountEditText extends EditText {

    private CharSequence temp;
    private int selectionStart;
    private int selectionEnd;
    private int maxNum = 500;

    public CountEditText(Context context) {
        super(context);
        initEditText();
    }

    public CountEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        initEditText();
    }

    public CountEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initEditText();
    }

    private void initEditText() {
        addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }
            @Override
            public void afterTextChanged(Editable s) {
                int number = maxNum - s.length();
                if (onEditTextCountLisener != null){
                    onEditTextCountLisener.setCount(s.length());
                }
                selectionStart = getSelectionStart();
                selectionEnd = getSelectionEnd();
                //System.out.println("start="+selectionStart+",end="+selectionEnd);
                if (temp.length() > maxNum) {
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionStart;
                    setText(s);
                    setSelection(tempSelection);//设置光标在最后
                }
            }
        });
    }

    public void setMaxNum(int maxNum) {
        this.maxNum = maxNum;
    }

    private OnEditTextCountLisener onEditTextCountLisener;

    public interface OnEditTextCountLisener{
        void setCount(int currentCount);
    }

    public void setOnEditTextCountLisener(OnEditTextCountLisener onEditTextCountLisener){
        this.onEditTextCountLisener = onEditTextCountLisener;
    }
}
